package com.liuyu.common.framework.insurance.picc.gd.converter;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName DateConverter
 * @Author: liuyu
 * @Date: Created in 2021/5/8 14:24
 * @Version: 1
 * @Modified By:
 */
public class LocalDateConverter implements Converter {
    /**
     *格式化当前系统日期
     */
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final String NULL = "null";

    @Override
    public void marshal(Object o, HierarchicalStreamWriter hierarchicalStreamWriter, MarshallingContext marshallingContext) {
        if (o == null) {
            hierarchicalStreamWriter.setValue("");
        } else {
            LocalDate date = (LocalDate) o;
            hierarchicalStreamWriter.setValue(date.format(DATE_TIME_FORMATTER));
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) {
        String text = hierarchicalStreamReader.getValue();
        if (text == null || "".equals(text.trim()) || NULL.equals(text.trim().toLowerCase())) {
            return null;
        }
        return LocalDate.parse(text, DATE_TIME_FORMATTER);
    }

    @Override
    public boolean canConvert(Class aClass) {
        return LocalDate.class == aClass;
    }
}
